package com.baselibrary.fragment

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.R
import com.baselibrary.activity.BaseFragment
import com.baselibrary.adapter.CommonDynamicAdapter
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.DynamicInfoBean
import com.baselibrary.databinding.FragmentDynamicBinding
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.utils.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * @author: merbng
 * @time: 2022/3/24 10:05
 * @description:
 */
class CommonDynamicFragment : BaseFragment() {
    private lateinit var mBinding: FragmentDynamicBinding
    private lateinit var mViewModel: BaseViewModel
    private var mCurrentPage = 1
    private var mCurrentCursor = "0"
    private var mIsLoadingMore = false
    private var mNoMoreData = false
    private var selectedPosition = 0
    private var selectedDeletePosition = 0
    private  var selectedStreamData: DynamicInfoBean.DataBeanX.DataBean?=null
    val mAdapter: CommonDynamicAdapter by lazy { CommonDynamicAdapter() }
    private var type = 1
    private var mTid: String = ""
    private var keyword: String = ""
    private var lastVisiblePosition = 1
    private var totalCount = 1

    companion object {
        const val DYNAMIC_TYPE_HOT = 1//最热
        const val DYNAMIC_TYPE_LATEST = 2//最新
        const val DYNAMIC_TYPE_TOPIC_SEARCH = 3//搜索话题
        const val DYNAMIC_TYPE_USER_PUBLISHED = 4//用户发布的动态
        const val DYNAMIC_TYPE_USER_LIKED = 5//用户赞过的动态
        const val DYNAMIC_TYPE_USER_COLLECTED = 6//用户收藏过的动态
        const val DYNAMIC_TYPE_USER_COLLECTED_TOPIC = 7//用户收藏过的话题
        const val DYNAMIC_TYPE_WINERY_MANAGER = 13//酒窖动态--酒窖动态管理(可删除操作)
        const val DYNAMIC_TYPE_WINERY = 9//酒窖详情--酒窖动态--酒窖动态列表（不可操作删除）
        fun newInstance(type: Int, typeUsedId: String): CommonDynamicFragment {
            val fragment = CommonDynamicFragment()
            val bundle = Bundle()
            bundle.putInt(Constants.KEY_DYNAMIC_TYPE, type)
            bundle.putString(Constants.KEY_TOPIC_ID, typeUsedId)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mBinding = getDataBinding<FragmentDynamicBinding>()
        initView()
        if (type != DYNAMIC_TYPE_TOPIC_SEARCH) {
            refreshData()
        }
        addObserver()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_dynamic
    }

    private fun initView() {
        if (arguments != null) {
            type = requireArguments().getInt(Constants.KEY_DYNAMIC_TYPE)
            mTid = requireArguments().getString(Constants.KEY_TOPIC_ID).checkValue()
        }
        mViewModel = getFragmentViewModelProvider(this).get(BaseViewModel::class.java)
        if (type == DYNAMIC_TYPE_HOT || type == DYNAMIC_TYPE_LATEST) {
            var params: ViewGroup.LayoutParams = mBinding.rvDiscover.layoutParams

            var marginParams: MarginLayoutParams? = null
            //获取view的margin设置参数
            marginParams = if (params is MarginLayoutParams) {
                params
            } else {
                //不存在时创建一个新的参数
                //基于View本身原有的布局参数对象
                MarginLayoutParams(params)
            }
            marginParams!!.setMargins(ScreenUtils.dpToPx(10), 0, ScreenUtils.dpToPx(10), 0)
        }

        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        if (type == DYNAMIC_TYPE_WINERY_MANAGER || type == DYNAMIC_TYPE_WINERY) {
            mBinding.rvDiscover.addItemDecoration(StaggeredItemDecoration(context, 8F, false))
        } else {
            mBinding.rvDiscover.addItemDecoration(StaggeredItemDecoration(context, 5F, false))
        }
        mBinding.rvDiscover.itemAnimator = null
        mBinding.rvDiscover.layoutManager = layoutManager
        mBinding.rvDiscover.isNestedScrollingEnabled = true
        mAdapter.setSourceName(getSourceName(type))
        mBinding.rvDiscover.adapter = mAdapter
        if (type == DYNAMIC_TYPE_WINERY) {
            //酒窖详情--酒窖动态--背景色为白色
            mBinding.rvDiscover.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.white))
        }
        mAdapter.setCallback(object : CommonDynamicAdapter.Callback {

            override fun onClickLike(position: Int, item: DynamicInfoBean.DataBeanX.DataBean) {
                selectedStreamData = item
                selectedPosition = position
                mViewModel.reqSupport(!item.isSupported, 4, item.id)
                SensorsDataManager.instance.giveLike(item.isSupported, getTypeName(type), "动态外部", SpanUtils.appendCut(item.content))
            }

        })

        mAdapter.setOnItemChildClickListener { _, view, position ->
            if (view.id == R.id.iv_delete_dynamic) {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    SensorsDataManager.instance.clickDeleteDynamic(SpanUtils.appendCut(mAdapter.data[position].content), TimeUtil.setYearMonthDay(mAdapter.data[position].publishTime))
                    selectedDeletePosition = position
                    PopUtils.showOkCancelDialog(activity as Activity, "确认删除该动态？", object : PopUtils.ICallBack {
                        override fun clickOk() {
                            if (type == DYNAMIC_TYPE_WINERY_MANAGER) {
                                ToastUtils.showShort(requireActivity().applicationContext, "删除成功")
                            }
                            mViewModel.deleteTimeline(mAdapter.data[position].id.toString())
                        }

                        override fun clickCancel() {

                        }

                    }, false, "确认", "取消")
                }
            }
        }
        mBinding.rvDiscover.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val positions = layoutManager.findLastVisibleItemPositions(null)
                //提前10个开始预加载
                if (dy > 0 && !mIsLoadingMore && positions[0] >= mAdapter.data.size - 10) {
                    mIsLoadingMore = true
                    mCurrentPage++
                    loadStream()
                }
                lastVisiblePosition = positions[0]
            }
        })
        mBinding.rlDiscoverSub.setOnRefreshListener { _ -> refreshData() }
        mBinding.rlDiscoverSub.setOnLoadMoreListener { _ ->
            if (mIsLoadingMore) {
                return@setOnLoadMoreListener
            }
            mCurrentPage++
            loadStream()
        }
    }

    private fun getTypeName(type: Int): String {
        return when (type) {
            DYNAMIC_TYPE_USER_PUBLISHED -> "个人主页-动态"
            DYNAMIC_TYPE_USER_COLLECTED -> "个人主页-收藏-动态"
            DYNAMIC_TYPE_USER_LIKED -> "个人主页-赞过"
            else -> ""
        }
    }

    private fun getSourceName(type: Int): String {
        return when (type) {
            DYNAMIC_TYPE_USER_PUBLISHED -> "我发布的动态页面"
            DYNAMIC_TYPE_USER_COLLECTED -> "收藏页面"
            DYNAMIC_TYPE_USER_LIKED -> "赞过的页面"
            else -> ""
        }
    }

    private fun loadStream() {
        if (!mNoMoreData) {
            when (type) {
                DYNAMIC_TYPE_HOT -> mViewModel.requestHotAndLatest(mCurrentPage.toString(), mTid, "hot")

                DYNAMIC_TYPE_LATEST -> mViewModel.requestHotAndLatest(mCurrentPage.toString(), mTid, "publishTime")

                DYNAMIC_TYPE_TOPIC_SEARCH -> mViewModel.requestSearchTopic(mCurrentPage.toString(), mTid, keyword)

                DYNAMIC_TYPE_USER_PUBLISHED -> {
                    if (mTid == SpUtils.getInstance().userId.toString()) {
                        mAdapter.setShowDelete(true)
                    }
                    mViewModel.requestUserTimeline(mCurrentCursor, mTid)
                }
                DYNAMIC_TYPE_USER_COLLECTED -> {
                    mAdapter.setShowDelete(false)
                    mViewModel.requestUserCollection(mCurrentCursor, "4", mTid)
                }
                DYNAMIC_TYPE_USER_LIKED -> {
                    mAdapter.setShowDelete(false)
                    mViewModel.requestUserLiked(mCurrentPage.toString(), mTid)
                }
                DYNAMIC_TYPE_WINERY_MANAGER -> {
                    mAdapter.setShowDelete(true)
                    mViewModel.requestUserTimeline(mCurrentCursor, mTid)
                }
                DYNAMIC_TYPE_WINERY -> {
                    mAdapter.setShowDelete(false)
                    mViewModel.requestUserTimeline(mCurrentCursor, mTid)
                }

            }
        }
    }

    private fun addObserver() {
        //瀑布流数据
        mViewModel.dynamicStreamLD.observe(viewLifecycleOwner, Observer {
            mBinding.rlDiscoverSub.finishRefresh()
            if (it?.data != null) {
                mCurrentCursor = it.nextCursor
                totalCount = it.totalCount
                if (type == DYNAMIC_TYPE_USER_COLLECTED) {
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_change_update_dynamic_total, it.totalCount)
                }
                if (mCurrentPage == 1) {
                    if (it.data.size == 0) {
                        mAdapter.data.clear()
                        mAdapter.notifyDataSetChanged()
                        EmptyViewUtil.isSelf = mTid == "${SpUtils.getInstance().userId}"
                        if (type == DYNAMIC_TYPE_WINERY_MANAGER) {
                            //酒窖动态
                            mBinding.flEmptyContainer.addView(EmptyViewUtil.getEmptyView4Winecellar(mBinding.rlDiscoverSub, "发布酒窖动态，把最近新鲜事分享给大家，添加成功后，在“线上酒窖”进行预览", R.drawable.ic_empty_demo_dynamic))
                        } else {
                            mBinding.flEmptyContainer.addView(EmptyViewUtil.getEmptyView(type, mBinding.rlDiscoverSub))
                        }
                        EventBusUtils.sendNotify1Value(MessageBus.msgId_load_dynamic_stream_is_have_data, false)
                    } else {
                        mBinding.flEmptyContainer.removeAllViews()
                        EventBusUtils.sendNotify1Value(MessageBus.msgId_load_dynamic_stream_is_have_data, true)
                        if (type == DYNAMIC_TYPE_USER_COLLECTED) {
                            mAdapter.setNewData(transferData(it.data))
                        } else {
                            mAdapter.setNewData(it.data)
                        }
                    }
                } else {
                    mBinding.rlDiscoverSub.finishLoadMore(1)
                    mIsLoadingMore = false
                    if (type == DYNAMIC_TYPE_USER_COLLECTED) {
                        mAdapter.addData(transferData(it.data))
                    } else {
                        mAdapter.addData(it.data)
                    }
                }
                if (type == DYNAMIC_TYPE_USER_LIKED || type == DYNAMIC_TYPE_HOT || type == DYNAMIC_TYPE_LATEST) {
                    if (it.totalCount <= 10 * mCurrentPage) {
                        mNoMoreData = true
                        mBinding.rlDiscoverSub.finishLoadMoreWithNoMoreData()
                    }
                } else {
                    if (!it.isHasnext) {
                        mNoMoreData = true
                        mBinding.rlDiscoverSub.finishLoadMoreWithNoMoreData()
                    }
                }
            } else {
                mNoMoreData = true
                mBinding.rlDiscoverSub.finishLoadMoreWithNoMoreData()
            }
        })
        //点赞数据
        mViewModel.supportLiveData.observe(viewLifecycleOwner, Observer { it ->
            if (it) {
                selectedStreamData?.let {
                it.supportNum = if (it.isSupported) it.supportNum.minus(1) else it.supportNum.plus(1)
                    it.isSupported = !it.isSupported
                }
                mAdapter.notifyItemChanged(selectedPosition)
            }
        })
        //删除动态数据
        mViewModel.deleteTimelineLD.observe(viewLifecycleOwner, Observer {
            ToastUtils.showShort(activity, "删除成功")
            mAdapter.data.removeAt(selectedDeletePosition)
            mAdapter.notifyDataSetChanged()
            if (selectedDeletePosition == 0 && mAdapter.data.size == 0) {
                if (type == DYNAMIC_TYPE_WINERY_MANAGER) {
                    //酒窖动态
                    mBinding.flEmptyContainer.addView(EmptyViewUtil.getEmptyView4Winecellar(mBinding.rlDiscoverSub, "发布酒窖动态，把最近新鲜事分享给大家，添加成功后，在“线上酒窖”进行预览", R.drawable.ic_empty_demo_dynamic))
                } else {
                    mBinding.flEmptyContainer.addView(EmptyViewUtil.getEmptyView(type, mBinding.rlDiscoverSub))
                }
            }
        })
    }


    private fun refreshData() {
        mCurrentPage = 1
        mCurrentCursor = "0"
        mNoMoreData = false
        mIsLoadingMore = false
        loadStream()
    }

    fun setDefaultView(topicName: String) {
        if (type == DYNAMIC_TYPE_TOPIC_SEARCH) {
            val view = LayoutInflater.from(context).inflate(R.layout.layout_search_empty_view, mBinding.rlDiscoverSub, false)
            view.findViewById<TextView>(R.id.tv_empty_tip).text = "在# ${topicName}中搜索"
            view.findViewById<ImageView>(R.id.iv_empty_img).setImageResource(R.drawable.img_search_empty)
            mBinding.flEmptyContainer.addView(view)
        }
    }

    fun searchKeywords(keyword: String) {
        this.keyword = keyword
        refreshData()
    }

    private fun transferData(datas: List<DynamicInfoBean.DataBeanX.DataBean>): List<DynamicInfoBean.DataBeanX.DataBean> {
        var newData: MutableList<DynamicInfoBean.DataBeanX.DataBean> = arrayListOf()
        for (data in datas) {
            if (data.timeline != null) {
                data.cover = data.timeline.cover
                data.content = data.timeline.content
                data.user = data.timeline.user
                data.isFans = data.timeline.isFans
                data.supportNum = data.timeline.supportNum
                data.isSupported = data.timeline.isSupported
                data.showType = data.timeline.showType
                data.id = data.timeline.id
            }
            newData.add(data)
        }
        return newData
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_change_dynamic_like_status) {
            for ((index, data) in mAdapter.data.withIndex()) {
                if (data.id == messageBus.param1) {
                    data.isSupported = !data.isSupported
                    data.supportNum = if (data.isSupported) data.supportNum.plus(1) else data.supportNum.minus(1)
                    mAdapter.notifyItemChanged(index)
                    break
                }
            }
        } else if (messageBus.codeType == MessageBus.DynamicNotice || messageBus.codeType == MessageBus.msgid_notify_publish_success) {
            if (type == DYNAMIC_TYPE_USER_PUBLISHED || type == DYNAMIC_TYPE_WINERY_MANAGER) {
                refreshData()
            }
        } else if (messageBus.codeType == MessageBus.msgId_dynamic_collection_false) {
            if (type == DYNAMIC_TYPE_USER_COLLECTED) {
                mAdapter.remove()
                if (mAdapter.data.size == 0) {
                    mBinding.flEmptyContainer.addView(EmptyViewUtil.getEmptyView(type, mBinding.rlDiscoverSub))
                }
            }
        }
    }

    override fun onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroyView()
    }

    private var hidden: Boolean = false

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        this.hidden = hidden
    }

    fun getProgress(): Double {
        return if (mBinding.rvDiscover.canScrollVertically(1)) {
            NumberUtils.getDouble(lastVisiblePosition, totalCount)
        } else {
            100.00
        }
    }
}